<?php

/**
 * This file is part of Switcher.
 * 
 * Switcher is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * Switcher is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with Switcher. If not, see <http://www.gnu.org/licenses/>.
 * 
 * @license http://www.opensource.org/licenses/gpl-3.0.html GPL-3.0
 */

namespace switcher\filters;

/**
 * The <b>FilterStack</b> class manages the filtering phases. It takes care
 * of the filters creation, the request and response filtering.
 * 
 * <p>This class shouldn't be used. Instances are built and consumed by the
 * <b>Switcher</b> class.</p>
 * 
 * @author Dri <switcher.framework@gmail.com>
 * @license http://www.opensource.org/licenses/gpl-3.0.html GPL-3.0
 * @package switcher\filters
 * @since 1.0.0
 * @see Filter
 */
final class FilterStack
{
	/**
	 * The actual filter stack.
	 * @var array
	 */
	private $filters = array();
	
	/**
	 * Constructor. Creates the filters declared in the configuration.
	 * 
	 * @param switcher\config\Config $config The configuration
	 * @throws UnexpectedValueException If a declared filter isn't a subclass of Filter
	 */
	public function __construct(\switcher\config\Config $config)
	{
		foreach ($config->filters as $item)
		{
			$filter = \switcher\utils\ReflectionHelper::createObject($item);
			
			if ( !is_subclass_of($filter, '\switcher\filters\Filter') )
			{
				throw new \UnexpectedValueException('Not a Filter : ' . get_class($filter));
			}
			
			\switcher\utils\ReflectionHelper::setProperty($filter, 'root', $config->root());
			\switcher\log\LoggerFactory::injectLogger($filter);
			
			array_push($this->filters, $filter);
		}
	}
	
	/**
	 * Execute all the request filtering from the first filter to the last.
	 */
	public function doFilterRequest()
	{
		$count = count($this->filters);
		
		for ($i = 0; $i < $count; $i++)
		{
			$this->filters[$i]->doFilterRequest();
		}
	}
	
	/**
	 * Execute all the response filtering from the last filter to the first.
	 * 
	 * @param string $response The original response
	 */
	public function doFilterResponse($response)
	{
		$count = count($this->filters);
		
		for ($i = $count - 1; $i >= 0; $i--)
		{
			$response = $this->filters[$i]->doFilterResponse($response);
		}
		
		return $response;
	}
}

?>